package com.frame.pageform.component.tree;

import java.util.*;

import com.frame.pageform.PageForm;
import com.frame.pageform.component.Json;

abstract public class TreeJson extends PageForm implements Json{

	private List trees;

	private String nodeId;

	/**
	 * 是否动态加载
	 */
	private boolean lazy=true;


	public String execute() throws Exception{
		if(getNodeId()==null)
			//加载根节点
			getRoot();
		trees=query();
		return getJson();
	}
	/**
	 * 子栏目列表，里面存放(com.frame.pageform.component.tree)
	 * @return
	 * @throws Exception
	 */
	abstract public List query() throws Exception;

	abstract public Object getRoot() throws Exception;

	public String getJson() {
		// TODO Auto-generated method stub
		if(trees==null)
			return "";
		//JSON输出格式
		TreeJosonObject jsonObj=new TreeJosonObject();
		for(int i=0;i<trees.size();i++){
			TreeNode tree=(TreeNode)trees.get(i);
			tree.setLazy(isLazy());
			jsonObj.add(tree);
		}
//			sortList();
//			String firstPid="";
//			List firstlist=new ArrayList();
//			Map map=new HashMap();
//			for(int i=0;i<trees.size();i++){
//				TreeNode tree=(TreeNode)trees.get(i);
//				if(i==0)
//					firstPid=tree.getPreId();
//				map.put(tree.getId(), tree);
//				if(firstPid.equals(tree.getPreId()))
//					firstlist.add(tree);
//				TreeNode pnode=(TreeNode)map.get(tree.getPreId());
//				if(pnode!=null){
//					
//					List clist=pnode.getChildList();
//					if(clist==null)
//						clist=new ArrayList();
//					clist.add(tree);
//					pnode.setChildList(clist);
//				}
//			}
//			for(int i=0;i<firstlist.size();i++){
//				TreeNode node=(TreeNode)firstlist.get(i);
//				jsonObj.add(node);
//			}
		return jsonObj.toString();
	}
	private void sortList(){
		Comparator comparator = new Comparator() {
			public int compare(Object obj1, Object obj2) {
				TreeNode node1 = (TreeNode) obj1;
				TreeNode node2 = (TreeNode) obj2;
				return Integer.parseInt(node1.getPreId()) - Integer.parseInt(node2.getPreId());
			}
		};
		Collections.sort(trees, comparator);
	}
	public void setTrees(List trees) {
		this.trees = trees;
	}

	public boolean isLazy() {
		return lazy;
	}
	public void setLazy(boolean lazy) {
		this.lazy = lazy;
	}
	public String getNodeId() {
		return nodeId;
	}
	public void setNodeId(String nodeId) {
		this.nodeId = nodeId;
	}
	public List getTrees() {
		return trees;
	}


}

